﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace MvcApplicationYoung.Controllers
{
    public class LoginController : Controller
    {
        MvcApplicationYoung.WcfServiceLibrary.IService1 _proxy;

        public LoginController()
        { InitWCFService(); }

        ~LoginController()
        {

        }

        public void InitWCFService()
        {
            //Http绑定
            WSHttpBinding httpBinding = new WSHttpBinding();
            EndpointAddress httpAddr = new EndpointAddress("http://localhost:8888/YoungMVC/Service.svc/test");
            _proxy = new ChannelFactory<MvcApplicationYoung.WcfServiceLibrary.IService1>(httpBinding, httpAddr).CreateChannel();

        }

        private bool CheckUser(string usr, string pwd)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine(((IChannel)_proxy).State);
                bool chk = _proxy.CheckUser(usr, pwd);
                ((IChannel)_proxy).Close();
                System.Diagnostics.Debug.WriteLine(((IChannel)_proxy).State);
                return chk;
            }
            catch
            { return false; }

        }

        [HttpGet]
        public ActionResult Index()
        {
#if DEBUG
            TempData["userName"] = "user1";
            TempData["password"] = "user1pass";
#else
            TempData["userName"] = Request.Params["userName"];
            TempData["password"] = Request.Params["password"];
#endif
            return View();
        }

        [ActionName("Index")]
        [HttpPost]
        public ActionResult Index_Post()
        {
            bool res = false;
            if (ModelState.IsValid)
            {
                if (CheckUser(Request.Form["fname"], Request.Form["fpwd"]))
                { res = true; }
            }

            if (res)
            {
                FormsAuthentication.SetAuthCookie(Request.Form["fname"], false);
                
                return RedirectToAction("LoginIn", "BodyGUI");
            }
            else
            { return RedirectToAction("Index", "Login", new { userName = Request.Form["fname"], password = Request.Form["fpwd"] }); }
        }

    }
}
